import SwiftUI

struct ListView: View {
    var item: MainPica = mainpicas[0]
    var bannersdata: [Banner] = banners
    @State var type: Int = 3
    @State var fav_type: Int = 0
    @Environment(\.dismiss) var dismiss
    @State private var progress: CGFloat = 0
    @State private var scrollOffset: CGFloat = 0
    @State private var showBarInfo: Bool = false
    @StateObject private var viewModel = MainPicaViewModel()
    @State private var currentPage: Int = 1
    @State private var isLoading = false // 用于防止重复加载
    @State private var hasAppeared = false
    
    @State var showSearchTags: Bool = false
    @State var tag:String = "全部分类"
    @State var order_by:Int = 1
    
    
    var body: some View {
        let items = viewModel.lists
        GeometryReader { proxy in
            ZStack(alignment: .top) {
                Rectangle()
                    .frame(height: proxy.size.height * 0.8)
                    .ignoresSafeArea()
                    .background(Color("BgColor1"))
                    .onAppear {
                        withAnimation(.linear(duration: 5.0).repeatForever(autoreverses: true)) {
                            self.progress = 1.0
                        }
                    }
                ScrollViewReader { scrollViewProxy in // 使用ScrollViewReader来控制滚动
                    ZStack(alignment: .top) {
                        ScrollView {
                            ListViewHeader(type: $type, scrollOffset: $scrollOffset, showBarInfo: $showBarInfo,showSearchTags:$showSearchTags,tag: $tag)
                            
                            Section {
                                LazyVStack{
                                    ForEach(0..<items.count, id: \.self) { index in
                                        if index % 5 == 0 {
                                            Group {
                                                LazyHStack {
                                                    ListCard(item: items[index], tag: "")
                                                        .frame(width: (proxy.size.width-40) / 2, height: 300)
                                                        .padding(.bottom, 0)
                                                        .id(items[index].id)  // 确保 NavigationLink 使用唯一标识符
                                                    
                                                    if index + 1 < items.count {
                                                        ListCard(item: items[index + 1], tag: "")
                                                            .frame(width: (proxy.size.width-40) / 2, height: 300)
                                                            .padding(.bottom, 0)
                                                            
                                                    }
                                                    
                                                }
                                                .padding(.horizontal, 10)
                                                
                                                LazyHStack {
                                                    if index + 2 < items.count {
                                                        ListCard(item: items[index + 2], tag: "")
                                                            .frame(width: (proxy.size.width-40) / 2, height: 300)
                                                            .padding(.bottom, 0)
                                                            
                                                    }
                                                    
                                                    if index + 3 < items.count {
                                                        ListCard(item: items[index + 3], tag: "")
                                                            .frame(width: (proxy.size.width-40) / 2, height: 300)
                                                            .padding(.bottom, 0)
                                                            
                                                    }
                                                }
                                                .padding(.horizontal, 10)
                                            }
                                        } else if index % 5 == 4 {
                                            ListCard(item: items[index], tag: "")
                                                .frame(width: proxy.size.width-30, height: 400)
                                                .padding(.bottom, 0)
                                               
                                        }
                                    }.padding(.top)
                                }
                                .background(GeometryReader { geo in
                                    Color.clear.preference(key: EndReachedKey.self, value: [geo.frame(in: .global).maxY])
                                })
                                .background(GeometryReader {
                                    Color.clear.preference(key: ViewOffsetKey.self,
                                                           value: -$0.frame(in: .global).origin.y)
                                })
                                .padding(.horizontal, 10)
                                .background(Color("BgColor1"))
                                
                            }
                            header: {
                                HStack {
                                    Text("已经加载\(currentPage)页")
                                        .font(.headline)
                                        .bold()
                                        .foregroundColor(.white)
                                        .padding()
                                    
                                    Spacer()
                                    
                                    Button {
                                        // 执行排序或其他操作
                                        withAnimation(.spring(response: 0.5, dampingFraction: 0.6, blendDuration: 0)) {
                                                            order_by = (order_by == 2) ? 1 : 2
                                                        }
                                        load_data()
                                    } label: {
                                        Image(systemName: "arrow.down")  // 带方框的下箭头
                                            .font(.headline)
                                            .foregroundStyle(.white)
                                            .rotationEffect(.degrees(order_by == 2 ? 180 : 0)) // 旋转180度
                                    }
                                    .padding(.trailing, 14)
                                }
                                .frame(maxWidth: .infinity, alignment: .leading)
                                .background(Color("BgColor1"))
                                .clipShape(UnevenRoundedRectangle(topLeadingRadius: 20.0, topTrailingRadius: 20.0))
                                .listRowInsets(EdgeInsets())
                            }
                            .listRowSeparator(.hidden)
                            .listSectionSpacing(0)
                            //                        .listRowBackground(Color.black)
                            .listRowInsets(EdgeInsets())
                            .background(Color("BgColor2"))
                        }
                        .onPreferenceChange(ViewOffsetKey.self) { offset in
                            if offset > -160 {
                                if !showBarInfo {
                                    triggerHapticFeedback()
                                }
                                showBarInfo = true
                            } else {
                                showBarInfo = false
                            }
                        }
                        .onPreferenceChange(EndReachedKey.self) { value in
                            if let maxY = value.last {
                                if maxY < proxy.frame(in: .global).maxY {
                                    loadNextPage()
                                }
                            }
                        }
                        .onAppear {
                            if !hasAppeared {
                                // 执行首次加载的代码
                                load_data()
                                hasAppeared = true
                            }
                        }
                        .onChange(of:tag) { oldValue, newValue in
                            showSearchTags = false
                            load_data()
                            withAnimation {
                                scrollViewProxy.scrollTo(0, anchor: .top)
                            }
                        }
                        .onChange(of:fav_type) { oldValue, newValue in
                            showSearchTags = false
                            load_data()
                            withAnimation {
                                scrollViewProxy.scrollTo(0, anchor: .top)
                            }
                            
                        }
                        .listStyle(PlainListStyle())
                        .scrollContentBackground(.hidden)
                        //.scrollIndicators(.hidden)
                        .padding(.top, 50)
                        .background(Color("BgColor2"))
                        
                        // 顶部导航栏
                        ListViewBar(showBarInfo:$showBarInfo,type: $type,showSearchTags:$showSearchTags,tag: $tag,fav_type: $fav_type)
                    }
                }
            }
            .background(Color("BgColor2"))
        }
        .sheet(isPresented: $showSearchTags) {
            ListViewTags(tag: $tag,type:$type)
                .background(Color("BgColor1"))
                .presentationDetents([.medium])
                .presentationDragIndicator(.hidden)
        }
        .navigationBarBackButtonHidden()
    }
    
    
    private func load_data() {
        currentPage = 1
        viewModel.get_list(type: type, page: currentPage,tag:tag,fav_type:fav_type,order_by:order_by)
    }
    
    private func loadNextPage() {
        isLoading = viewModel.isLoading
        if !isLoading {
            triggerHapticFeedback()
            print("加载下一页: 当前页数 \(currentPage)")
            currentPage += 1
            viewModel.get_list(type: type, page: currentPage,tag:tag, fav_type: fav_type,order_by:order_by)
            
        }
    }
    
    
}


#Preview {
    ListView()
}
